package com.example.financechain.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.financechain.Utils.JWTUtils;
import com.example.financechain.Utils.JsonData;
import com.example.financechain.Utils.UserThreadLocal;
import com.example.financechain.domain.entity.Role;
import com.example.financechain.service.IRoleService;
import com.example.financechain.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.spi.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

//@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*
        需要判断请求接口路径是否为handlermethod
        判断token是否为空
        如果token 不为空 登录验证

         */
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");


        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (token == null){
            JsonData jsonData = JsonData.buildError("未登录");
            response.setContentType("application/json;charset=utf-8");
            //不能直接给到前端，是因为要转化成json
            response.getWriter().print(JSON.toJSONString(jsonData));
            return false;
        }

        Role role = null;
        Map<String, Object> tokenInfo = JWTUtils.checkToken(token);
        if (tokenInfo != null) {
            // 验证通过，获取 Token 中的信息
             Integer userId = (Integer) tokenInfo.get("userId");
             log.info(userId.toString());

            //role = roleService.getById(userId);
            role =  JSON.parseObject(stringRedisTemplate.opsForValue().get(userId.toString()),Role.class);

        } else {
            // 验证失败，Token 不合法或已过期
            // TODO: 处理异常情况
            JsonData jsonData = JsonData.buildError("登录已过期");
            response.setContentType("application/json;charset=utf-8");
            //不能直接给到前端，是因为要转化成json
            response.getWriter().print(JSON.toJSONString(jsonData));
            return false;

        }

        //是登录状态，放行

        //登录验证成功，放行
        //我希望在controller中 直接获取用户的信息 怎么获取?
        UserThreadLocal.set(role);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

        //！！！必须要的，不然内存会溢出
        UserThreadLocal.remove();
    }
}
